<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org" 
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout/base}">
<head>
    <title>预警中心 - 智能营养管理系统</title>
</head>
<body>
    <div layout:fragment="content">
        <!-- 页面标题 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-exclamation-triangle me-2"></i>营养预警中心</h2>
            <div class="d-flex gap-2">
                <button class="btn btn-outline-primary" onclick="refreshAlerts()">
                    <i class="fas fa-sync-alt me-1"></i>刷新
                </button>
                <a th:href="@{/alerts/settings}" class="btn btn-outline-secondary">
                    <i class="fas fa-cog me-1"></i>设置
                </a>
            </div>
        </div>

        <!-- 预警概览卡片 -->
        <div class="row mb-4">
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <div class="text-danger mb-2">
                            <i class="fas fa-exclamation-circle" style="font-size: 2.5rem;"></i>
                        </div>
                        <h5 class="card-title">今日预警</h5>
                        <h3 class="text-danger" id="todayAlertCount" th:text="${todayAlert.totalAlertCount}">0</h3>
                        <small class="text-muted">条预警信息</small>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <div class="text-danger mb-2">
                            <i class="fas fa-exclamation-triangle" style="font-size: 2.5rem;"></i>
                        </div>
                        <h5 class="card-title">高优先级</h5>
                        <h3 class="text-danger" id="highPriorityCount" th:text="${todayAlert.highPriorityAlerts.size()}">0</h3>
                        <small class="text-muted">需要立即关注</small>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <div class="text-warning mb-2">
                            <i class="fas fa-exclamation-circle" style="font-size: 2.5rem;"></i>
                        </div>
                        <h5 class="card-title">中优先级</h5>
                        <h3 class="text-warning" id="mediumPriorityCount" th:text="${todayAlert.mediumPriorityAlerts.size()}">0</h3>
                        <small class="text-muted">建议调整</small>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <div class="text-info mb-2">
                            <i class="fas fa-info-circle" style="font-size: 2.5rem;"></i>
                        </div>
                        <h5 class="card-title">低优先级</h5>
                        <h3 class="text-info" id="lowPriorityCount" th:text="${todayAlert.lowPriorityAlerts.size()}">0</h3>
                        <small class="text-muted">参考建议</small>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- 今日预警详情 -->
            <div class="col-lg-8">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="fas fa-bell me-2"></i>今日预警详情</h5>
                        <span class="badge bg-secondary" th:text="${#temporals.format(today, 'yyyy-MM-dd')}">2024-01-01</span>
                    </div>
                    <div class="card-body">
                        <!-- 无预警状态 -->
                        <div th:if="${!todayAlert.hasAlerts()}" class="text-center py-4">
                            <i class="fas fa-check-circle text-success" style="font-size: 4rem;"></i>
                            <h4 class="text-success mt-3">今日营养状况良好</h4>
                            <p class="text-muted">没有发现营养预警，请继续保持！</p>
                        </div>
                        
                        <!-- 有预警状态 -->
                        <div th:if="${todayAlert.hasAlerts()}">
                            <!-- 高优先级预警 -->
                            <div th:if="${!todayAlert.highPriorityAlerts.empty}" class="mb-4">
                                <h6 class="text-danger mb-3">
                                    <i class="fas fa-exclamation-triangle me-2"></i>高优先级预警
                                </h6>
                                <div th:each="msg : ${todayAlert.highPriorityAlerts}" class="alert alert-danger d-flex align-items-start">
                                    <i class="fas fa-exclamation-triangle me-3 mt-1"></i>
                                    <div>
                                        <p class="mb-0 mt-1" th:text="${msg}">预警信息</p>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 中优先级预警 -->
                            <div th:if="${!todayAlert.mediumPriorityAlerts.empty}" class="mb-4">
                                <h6 class="text-warning mb-3">
                                    <i class="fas fa-exclamation-circle me-2"></i>中优先级预警
                                </h6>
                                <div th:each="msg : ${todayAlert.mediumPriorityAlerts}" class="alert alert-warning d-flex align-items-start">
                                    <i class="fas fa-exclamation-circle me-3 mt-1"></i>
                                    <div>
                                        <p class="mb-0 mt-1" th:text="${msg}">预警信息</p>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 低优先级预警 -->
                            <div th:if="${!todayAlert.lowPriorityAlerts.empty}">
                                <h6 class="text-info mb-3">
                                    <i class="fas fa-info-circle me-2"></i>低优先级预警
                                </h6>
                                <div th:each="msg : ${todayAlert.lowPriorityAlerts}" class="alert alert-info d-flex align-items-start">
                                    <i class="fas fa-info-circle me-3 mt-1"></i>
                                    <div>
                                        <p class="mb-0 mt-1" th:text="${msg}">预警信息</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 操作按钮 -->
                        <div class="text-center mt-4" th:if="${todayAlert.hasAlerts()}">
                            <a th:href="@{/nutrition/dashboard}" class="btn btn-primary me-2">
                                <i class="fas fa-chart-line me-1"></i>查看营养详情
                            </a>
                            <a th:href="@{/meals}" class="btn btn-success">
                                <i class="fas fa-utensils me-1"></i>去点餐
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 预警统计和历史 -->
            <div class="col-lg-4">
                <!-- 预警统计 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-chart-pie me-2"></i>预警统计</h5>
                    </div>
                    <div class="card-body">
                        <div id="alertStatisticsContainer" class="position-relative" style="min-height: 220px;">
                            <canvas id="alertStatisticsChart" height="200"></canvas>
                        </div>
                        <div class="mt-3">
                            <button class="btn btn-outline-primary btn-sm w-100" onclick="loadStatistics()">
                                <i class="fas fa-sync-alt me-1"></i>更新统计
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- 预警历史 -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-history me-2"></i>最近预警</h5>
                    </div>
                    <div class="card-body">
                        <div th:if="${alertHistory.empty}" class="text-center text-muted py-3">
                            <i class="fas fa-check-circle" style="font-size: 2rem;"></i>
                            <p class="mt-2 mb-0">最近7天无预警记录</p>
                        </div>
                        
                        <div th:unless="${alertHistory.empty}">
                            <div th:each="historyAlert : ${alertHistory}" class="border-bottom pb-2 mb-2">
                                <div class="d-flex justify-content-between align-items-center">
                                    <span class="fw-bold" th:text="${#temporals.format(historyAlert.date, 'MM-dd')}">日期</span>
                                    <span class="badge bg-secondary" th:text="${historyAlert.totalAlertCount} + '条'">预警数</span>
                                </div>
                                <div class="small text-muted mt-1">
                                    <span th:if="${!historyAlert.highPriorityAlerts.empty}" 
                                          class="badge bg-danger me-1" th:text="'高:' + ${historyAlert.highPriorityAlerts.size()}">高</span>
                                    <span th:if="${!historyAlert.mediumPriorityAlerts.empty}" 
                                          class="badge bg-warning me-1" th:text="'中:' + ${historyAlert.mediumPriorityAlerts.size()}">中</span>
                                    <span th:if="${!historyAlert.lowPriorityAlerts.empty}" 
                                          class="badge bg-info me-1" th:text="'低:' + ${historyAlert.lowPriorityAlerts.size()}">低</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="text-center mt-3">
                            <a href="#" class="btn btn-outline-secondary btn-sm" onclick="loadAlertTrend()">
                                <i class="fas fa-chart-line me-1"></i>查看趋势
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <th:block layout:fragment="page-scripts">
        <script>
            let alertStatisticsChart;
            let statsIsFallback = false;
            
            // 刷新预警信息
            function refreshAlerts() {
                fetch('/alerts/api/current')
                    .then(response => response.json())
                    .then(data => {
                        document.getElementById('todayAlertCount').textContent = data.alertCount;
                        document.getElementById('highPriorityCount').textContent = data.highPriorityCount;
                        document.getElementById('mediumPriorityCount').textContent = data.mediumPriorityCount;
                        document.getElementById('lowPriorityCount').textContent = data.lowPriorityCount;
                        
                        App.showMessage('success', '预警信息已更新');
                        
                        // 如果有新的高优先级预警，可以考虑刷新页面
                        if (data.highPriorityCount > 0) {
                            setTimeout(() => {
                                window.location.reload();
                            }, 2000);
                        }
                    })
                    .catch(error => {
                        App.showMessage('error', '刷新失败，请稍后重试');
                        console.error('Error:', error);
                    });
            }
            
            // 加载预警统计
            function loadStatistics() {
                fetch('/alerts/api/statistics?days=30')
                    .then(response => response.json())
                    .then(data => {
                        if (typeof window.Chart === 'undefined') {
                            // 无法加载Chart.js时，使用回退渲染
                            renderStatisticsFallback(data.statistics);
                            return;
                        }
                        updateStatisticsChart(data);
                    })
                    .catch(error => {
                        console.error('Error loading statistics:', error);
                        // 网络或其他错误时，尝试回退渲染空数据
                        if (document.getElementById('alertStatisticsChart')) {
                            const fallback = { high: 0, medium: 0, low: 0 };
                            renderStatisticsFallback(fallback);
                        }
                    });
            }
            
            // 回退渲染（当Chart.js不可用时显示简化统计）
            function renderStatisticsFallback(statistics) {
                let container = document.getElementById('alertStatisticsContainer');
                if (!container) {
                    const canvas = document.getElementById('alertStatisticsChart');
                    if (!canvas) return;
                    container = canvas.parentElement;
                }
                const html = `
                    <div class="small">
                        <div class="d-flex justify-content-between mb-2">
                            <span class="text-danger">高优先级</span>
                            <span><strong>${statistics.high}</strong></span>
                        </div>
                        <div class="progress mb-3" style="height: 6px;">
                            <div class="progress-bar bg-danger" role="progressbar" style="width: ${statistics.high}%"></div>
                        </div>
                        <div class="d-flex justify-content-between mb-2">
                            <span class="text-warning">中优先级</span>
                            <span><strong>${statistics.medium}</strong></span>
                        </div>
                        <div class="progress mb-3" style="height: 6px;">
                            <div class="progress-bar bg-warning" role="progressbar" style="width: ${statistics.medium}%"></div>
                        </div>
                        <div class="d-flex justify-content-between mb-2">
                            <span class="text-info">低优先级</span>
                            <span><strong>${statistics.low}</strong></span>
                        </div>
                        <div class="progress" style="height: 6px;">
                            <div class="progress-bar bg-info" role="progressbar" style="width: ${statistics.low}%"></div>
                        </div>
                        <div class="text-muted mt-2">图表库不可用，已显示数值概览</div>
                    </div>
                `;
                container.innerHTML = html;
                statsIsFallback = true;
            }

            // 更新统计图表
            function updateStatisticsChart(data) {
                const container = document.getElementById('alertStatisticsContainer');
                if (!window.Chart) { renderStatisticsFallback(data.statistics); return; }
                let canvas = document.getElementById('alertStatisticsChart');
                if (!canvas) {
                    // 若之前为回退视图，恢复canvas
                    container.innerHTML = '<canvas id="alertStatisticsChart" height="200"></canvas>';
                    canvas = document.getElementById('alertStatisticsChart');
                    statsIsFallback = false;
                }
                const ctx = canvas.getContext('2d');
                
                if (alertStatisticsChart) {
                    alertStatisticsChart.destroy();
                    alertStatisticsChart = null;
                }
                
                alertStatisticsChart = new Chart(ctx, {
                    type: 'doughnut',
                    data: {
                        labels: ['高优先级', '中优先级', '低优先级'],
                        datasets: [{
                            data: [
                                data.statistics.high,
                                data.statistics.medium,
                                data.statistics.low
                            ],
                            backgroundColor: [
                                '#dc3545',
                                '#ffc107',
                                '#17a2b8'
                            ],
                            borderWidth: 2,
                            borderColor: '#fff'
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        animation: { duration: 0 },
                        plugins: {
                            legend: {
                                position: 'bottom',
                                labels: {
                                    padding: 10,
                                    usePointStyle: true
                                }
                            }
                        }
                    }
                });
            }
            
            // 加载预警趋势
            function loadAlertTrend() {
                // 这里可以打开一个模态框显示趋势图
                // 或者跳转到专门的趋势分析页面
                App.showMessage('info', '预警趋势分析功能开发中...');
            }
            
            // 页面加载完成后初始化
            document.addEventListener('DOMContentLoaded', function() {
                loadStatistics();
                
                // 每5分钟自动刷新一次预警信息
                setInterval(refreshAlerts, 5 * 60 * 1000);
            });
        </script>
    </th:block>
</body>
</html>
